<?php
namespace app\core\controller;

use think\Controller;

// 文件上传下载
class File extends Controller {
	// 上传
	public function upload() {
		$return = array('status' => 1, 'info' => lang('_SUCCESS_UPLOAD_'), 'data' => '');
		// 调用文件上传组件上传文件 
		$File = db('Admin/File');
		$file_driver = config('DOWNLOAD_UPLOAD_DRIVER');
		$info = $File->upload(
			$_FILES,
			config('DOWNLOAD_UPLOAD'),
			config('DOWNLOAD_UPLOAD_DRIVER'),
			config("UPLOAD_{$file_driver}_CONFIG")
		);

		if ($info) {
			$return['data'] = think_encrypt(json_encode($info['download']));
		} else {
			$return['status'] = 0;
			$return['info'] = $File->getError();
		}
		$this->ajaxReturn($return);
	}

	// 下载文件
	public function downloadFile($id=null) {
		if (empty($id) || !is_numeric($id)) {
			$this->error(lang('_ERROR_PARAM_').lang('_EXCLAMATION_'));
		}
		$info = db('file')->find($id);
		if(empty($info)){
			$this->error( lang('_DOCUMENT_ID_INEXISTENT_').lang('_COLON_')."{$id}");
			return false;
		}
		$File = db('Admin/File');
		$root ='.';
		$call = '';
		if(false === $File->download($root, $info['id'], $call, $info['id']) ) $this->error( $File->getError());
	}
	// 上传文件
	public function uploadFile() {
		$return = [
			'status' => 1,
			'info' => lang('upload success'),
			'data' => ''
		];

		$file = request()->file("file");
		$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/picture');


		if ( $info ) {
            if ( isset($info->id) && is_numeric($info->id) ) continue; // 已经上传的
            
            $oinfo = $info->getInfo();

            $data['name'] = $oinfo['name'];
            // $data['savename'] = $info->saveName;
            $data['savepath'] = $info->getSaveName();
            $data['md5'] = $info->hash('md5');
            $data['sha1'] = $info->hash('sha1');
            // $data['ext'] = $info->saveName;
            $data['mime'] = $info->getMime();
            $data['size'] = $oinfo['size'];
            $data['driver'] = 'local';
            $data['create_time'] = time();

            if ( $id = db("common_file")->insertGetId($data) ) {
                $return['data']['file']['id'] = $id;
                $return['data']['file']['name'] = $oinfo['name'];
            } else {
            	$return['status'] = 0;
                $return['info'] = '记录到数据库失败！';
            }
		} else {
			$return['status'] = 0;
			$return['info'] = $info->getError();
		}

		return json($return);
	}
	// 上传图片
	public function uploadPicture() {
		$return = [
			'status' => 1,
			'info' => lang('upload success'),
			'data' => ''
		];

		$file = request()->file("file");
		$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/picture');

		if ( $info ) {
            if ( isset($info->id) && is_numeric($info->id) ) continue; // 已经上传的
            
            $oinfo = $info->getInfo();

            $data['name'] = $oinfo['name'];
            // $data['url'] = $info->saveName;
            $data['path'] =$info->getSaveName();
            $data['md5'] = $info->hash('md5');
            $data['sha1'] = $info->hash('sha1');
            $data['size'] = $oinfo['size'];
            $data['type'] = 'local';
            $data['create_time'] = time();
            $data['width'] = 0;
            $data['height'] = 0;

            if ( $id = db("common_picture")->insertGetId($data) ) {
                $return['data']['file']['id'] = $id;
                $return['data']['file']['url'] = "/uploads/picture/".$info->getSaveName();
            } else {
            	$return['status'] = 0;
                $return['info'] = '记录到数据库失败！';
            }
		} else {
			$return['status'] = 0;
			$return['info'] = $info->getError();
		}

		return json($return);
	}
	// 上传文件 base64
	public function uploadPictureBase64() {
		$aData = $_POST['data'];

		if ($aData == '' || $aData == 'undefined' ) $this->ajaxReturn(array('status'=>0,'info'=>'参数错误'));

		if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $aData, $result)) {
			$base64_body = substr(strstr($aData, ','), 1);
			empty($aExt) && $aExt = $result[2];
		} else {
			$base64_body = $aData;
		}

		if(!in_array($aExt,array('jpg','gif','png','jpeg')) ) $this->ajaxReturn(array('status'=>0,'info'=>'非法操作,上传照片格式不符。'));
		$hasPhp=base64_decode($base64_body);

		if (strpos($hasPhp, '<?php') !==false ) $this->ajaxReturn(array('status' => 0, 'info' => '非法操作'));

		$pictureModel = db('Picture');

		$md5 = md5($base64_body);
		$sha1 = sha1($base64_body);

		$check = $pictureModel->where(array('md5' => $md5, 'sha1' => $sha1))->find();

		if ($check) {
			$return['id'] = $check['id'];
			$return['path'] = render_picture_path($check['path']);
			$this->ajaxReturn(array('status'=>1,'id'=>$return['id'],'path'=> $return['path']));
		} else {
			$driver = modconfig('PICTURE_UPLOAD_DRIVER','local','config');
			$driver = check_driver_is_exist($driver);
			$date = date('Y-m-d');
			$saveName = uniqid();
			$savePath = '/Uploads/Picture/' . $date . '/';

			$path = $savePath . $saveName . '.' . $aExt;
			if($driver == 'local'){
				//本地上传
				mkdir('.' . $savePath, 0777, true);
				$data = base64_decode($base64_body);
				$rs = file_put_contents('.' . $path, $data);
			}
			else{
				$rs = false;
				//使用云存储
				$name = get_addon_class($driver);
				if (class_exists($name)) {
					$class = new $name();
					if (method_exists($class, 'uploadBase64')) {
						$path = $class->uploadBase64($base64_body,$path);
						$rs = true;
					}
				}
			}
			if ($rs) {
				$pic['type'] = $driver;
				$pic['path'] = $path;
				$pic['md5'] = $md5;
				$pic['sha1'] = $sha1;
				$pic['status'] = 1;
				$pic['create_time'] = time();
				$id = $pictureModel->add($pic);
				$this->ajaxReturn (array('status'=>1,'id' => $id, 'path' => render_picture_path($path)));
			} else {
				$this->ajaxReturn(array('status'=>0,'图片上传失败。'));
			}
		}
	}

	// 上传图片
	public function uploadPictureUM() {
		header("Content-Type:text/html;charset=utf-8");

		$return = array('status' => 1, 'info' => lang('_SUCCESS_UPLOAD_'), 'data' => '');

		// 实际有用的数据只有name和state，这边伪造一堆数据保证格式正确
		$originalName = 'u=2830036734,2219770442&fm=21&gp=0.jpg';
		$newFilename = '14035912861705.jpg';
		$filePath = 'upload\/20140624\/14035912861705.jpg';
		$size = '7446';
		$type = '.jpg';
		$status = 'success';
		$rs = array(
			"originalName" => $originalName,
			'name' => $newFilename,
			'url' => $filePath,
			'size' => $size,
			'type' => $type,
			'state' => $status,
			'original' => $_FILES['upfile']['name']
		);

		$Picture = db('admin/picture');

		$setting = config('EDITOR_UPLOAD');
		$setting['rootPath'] = './Uploads/Editor/Picture/';

		$driver = modconfig('PICTURE_UPLOAD_DRIVER','local','config');
		$driver = check_driver_is_exist($driver);
		$uploadConfig = get_upload_config($driver);

		$info = $Picture->upload(
			$_FILES,
			$setting,
			$driver,
			$uploadConfig
		);

		if ($info) {
			$return['status'] = 1;
			if ( $info['Filedata'] ) $return = array_merge($info['Filedata'], $return);
			if ( $info['download'] ) $return = array_merge($info['download'], $return);
			$rs['state'] = 'SUCCESS';
			$rs['url'] = $info['upfile']['path'];
			if ($type == 'ajax') {
				echo json_encode($rs);
				exit;
			} else {
				echo json_encode($rs);
				exit;
			}
		} else {
			$return['state'] = 0;
			$return['info'] = $Picture->getError();
		}

		$this->ajaxReturn($return);
	}
	// 上传文件
	public function uploadFileUE() {
		$return = array('status' => 1, 'info' => lang('_SUCCESS_UPLOAD_'), 'data' => '');

		//实际有用的数据只有name和state，这边伪造一堆数据保证格式正确
		$originalName = 'u=2830036734,2219770442&fm=21&gp=0.jpg';
		$newFilename = '14035912861705.jpg';
		$filePath = 'upload\/20140624\/14035912861705.jpg';
		$size = '7446';
		$type = '.jpg';
		$status = 'success';
		$rs = array(
			'name' => $newFilename,
			'url' => $filePath,
			'size' => $size,
			'type' => $type,
			'state' => $status
		);

		/* 调用文件上传组件上传文件 */
		$File = db('Admin/File');

		$driver = modconfig('DOWNLOAD_UPLOAD_DRIVER','local','config');
		$driver = check_driver_is_exist($driver);
		$uploadConfig = get_upload_config($driver);

		$setting = config('EDITOR_UPLOAD');
		$setting['rootPath']='./Uploads/Editor/File/';


		$setting['exts'] = 'jpg,gif,png,jpeg,zip,rar,tar,gz,7z,doc,docx,txt,xml,xlsx,xls,ppt,pptx,pdf';
		$info = $File->upload(
			$_FILES,
			$setting,
			$driver,
			$uploadConfig
		);

		if ($info) {
			$return['data'] = $info;

			$rs['original'] = $info['upfile']['name'];
			$rs['state'] = 'SUCCESS';
			$rs['url'] =  strpos($info['upfile']['savepath'], 'http://') === false ?  __ROOT__.$info['upfile']['savepath'].$info['upfile']['savename']:$info['upfile']['savepath'];
			$rs['size'] = $info['upfile']['size'];
			$rs['title'] = $info['upfile']['savename'];


			if ($type == 'ajax') {
				echo json_encode($rs);
				exit;
			} else {
				echo json_encode($rs);
				exit;
			}
		} else {
			$return['status'] = 0;
			$return['info'] = $File->getError();
		}

		$this->ajaxReturn($return);
	}

	// 上传头像
	public function uploadAvatar() {
		$aUid = I('get.uid',0,'intval');

		mkdir ("./Uploads/Avatar/".$aUid);

		$files = $_FILES;
		$setting  = config('PICTURE_UPLOAD');

		$driver = modconfig('PICTURE_UPLOAD_DRIVER','local','config');
		$driver = check_driver_is_exist($driver);
		$uploadConfig = get_upload_config($driver);

		$setting['rootPath'] = './Uploads/Avatar';
		$setting['saveName'] = array('uniqid', '/'.$aUid.'/');
		$setting['savepath'] = '';
		$setting['subName'] = '';
		$setting['replace'] = true;

		if (strtolower(config('PICTURE_UPLOAD_DRIVER'))  == 'sae') { // sae
			config(require_once(APP_PATH . 'Common/Conf/config_sae.php'));

			$Upload = new \Think\Upload($setting,config('PICTURE_UPLOAD_DRIVER'), array(config('UPLOAD_SAE_CONFIG')));
			$info = $Upload->upload($files);

			$config=config('UPLOAD_SAE_CONFIG');
			if ($info) { //文件上传成功，记录文件信息
				foreach ($info as $key => &$value) {
					$value['path'] = $config['rootPath'] . 'Avatar/' . $value['savepath'] . $value['savename']; //在模板里的url路径

				}
				/* 设置文件保存位置 */
				$this->_auto[] = array('location', 'Ftp' === $driver ? 1 : 0, self::MODEL_INSERT);
			}
		}else{ // 正常模式
			$Upload = new \Think\Upload($setting, $driver, $uploadConfig);
			$info = $Upload->upload($files);
		}
		if ($info) { //文件上传成功，不记录文件
			$return['status'] = 1;
			if ($info['Filedata']) {
				$return = array_merge($info['Filedata'], $return);
			}
			if ($info['download']) {
				$return = array_merge($info['download'], $return);
			}
			/*适用于自动表单的图片上传方式*/
			if ($info['file']) {
				$return['data']['file'] = $info['file'];

				$path = $info['file']['url'] ? $info['file']['url'] : "./Uploads/Avatar".$info['file']['savename'];
				$src = $info['file']['url'] ? $info['file']['url'] : __ROOT__."/Uploads/Avatar".$info['file']['savename'];
				// $return['data']['file']['path'] =;
				$return['data']['file']['path'] =$path;
				$return['data']['file']['src']=$src;
				$size =  getimagesize($path);
				$return['data']['file']['width'] =$size[0];
				$return['data']['file']['height'] =$size[1];
				$return['data']['file']['time'] =time();
			}
		} else {
			$return['status'] = 0;
			$return['info'] = $Upload->getError();
		}

		$this->ajaxReturn($return);
	}
}